extends Node

var items = {}
var money = 100

signal money_changed
signal items_changed
signal item_removed(item_def_amount)

class Inventory_item:
	var definition
	var amount = 1
	func _init(d):
		definition = d

func _ready():
	debug_generate()

func debug_generate():
	var definitions = $catalog.definitions
	gain_item(definitions["cotton_candy"])
	gain_item(definitions["cotton_candy"])
	gain_item(definitions["cotton_candy"])
	gain_item(definitions["onion_helmet"])
	gain_item(definitions["broken_sword"])
	
func modify_money(diff):
	var old = money
	money += diff
	emit_signal("money_changed", money, old, diff)
	
func gain_item(d):
	if not d is Item_definition:
		return gain_item(d.definition)
	var id = d.id
	if self.items.has(id):
		self.items[id].amount += 1
	else:
		self.items[id] = Inventory_item.new(d)
	emit_signal("items_changed")

func lose_item(id):
	if not id is String:
		return lose_item(id.definition.id)
	var item = null
	if self.items.has(id):
		if self.items[id].amount > 1:
			self.items[id].amount -= 1
			item = self.items[id]
		else:
			self.items[id].amount = 0
			item = self.items[id]
			self.items.erase(id)
	emit_signal("items_changed")
	emit_signal("item_removed", item)
	return item

func copy_merged_with_spots(spots):
	var copy = self.duplicate()
	for key in self.items.keys():
		var it = items[key]
		var new = Inventory_item.new(it.definition)
		new.amount = it.amount
		copy.items[key] = new
	for spot in spots:
		if spot.item:
			copy.gain_item(spot.item)
	return copy
